package com.clp.protocol.iec104.apdu.asdu.infoobj.qua;

import com.clp.protocol.iec104.definition.TypeTag;
import com.clp.protocol.iec104.definition.quatype.TpQuaType;
import com.clp.protocol.core.pdu.nbytepdu.BaseNBytePduClip;
import com.clp.protocol.core.pdu.ByteToStringFormat;
import com.clp.protocol.core.utils.ByteUtil;
import io.netty.buffer.ByteBuf;
import lombok.Getter;

import java.util.Objects;
import java.util.function.Consumer;

/**
 * 电度量召唤限定词（总召唤101）
 */
@Getter
public class C_CI_NA_1_Qua extends Qua {
    private TpQuaType type;

    public C_CI_NA_1_Qua() {
        this(null);
    }

    public C_CI_NA_1_Qua(TpQuaType tpQuaType) {
        super(TypeTag.C_CI_NA_1);
        this.type = tpQuaType;
    }

    @Override
    public C_CI_NA_1_Qua refreshFrom(ByteBuf buf) {
        this.type = TpQuaType.gain(buf.readByte());
        return this;
    }

    @Override
    public boolean isValid() {
        return type != null;
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        buf.writeByte(type.getVal());
    }

    @Override
    public void writeFormattedByteStringsTo(StringBuilder sb, String frameClipBytesSeparator, String byteSeparator, ByteToStringFormat byteFormat) {
        sb.append(byteFormat.format(type.getVal()));
    }

    @Override
    public void writeSimpleDescriptionTo(StringBuilder sb) {
        sb.append(ByteUtil.byteToHexStr(type.getVal(), true));
    }

    @Override
    public void writeDetailDescriptionTo(StringBuilder sb) {
        sb.append(type.getDesc()).append("(").append(ByteUtil.byteToHexStr(type.getVal(), true)).append(")");
    }

    @Override
    protected void forEachOneLevelChild(Consumer<BaseNBytePduClip<?>> consumer) {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        C_CI_NA_1_Qua that = (C_CI_NA_1_Qua) o;
        return type == that.type;
    }

    @Override
    public int hashCode() {
        return Objects.hash(type);
    }
}
